package com.cityeye.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cityeye.dao.AbstractEntityDao;
import com.cityeye.dao.DepartmentDao;
import com.cityeye.entity.Department;
import com.cityeye.form.DepartmentForm;
import com.cityeye.util.QryKeys;

public class DepartmentAction extends AbsListPageAction<Department> {

	public ActionForward queryJd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ActionForward relogin=checkLogin(mapping,request);
		if(relogin!=null)return relogin;
		
		request.setAttribute("department_type", 2);		
		ActionForward forward= super.query(mapping, form, request, response);
		DepartmentDao dao= new DepartmentDao();
		List<Department> quDepts = dao.findByProperty(Department.class, "type", DepartmentDao.TYPE_QU);
		request.setAttribute("qudepts", quDepts);

		return forward;
	}
	
	public ActionForward queryQu(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ActionForward relogin=checkLogin(mapping,request);
		if(relogin!=null)return relogin;
		
		request.setAttribute("department_type", 1);
		return super.query(mapping, form, request, response);
	}
	
	protected Map<String,Object> getQryConditions(HttpServletRequest request,boolean useSessionQry){		
		Map<String,Object> mapAttrs = super.getQryConditions(request,useSessionQry);
		if(request.getAttribute("department_type")!=null){
			mapAttrs.put("type",request.getAttribute("department_type"));
		}		
		
		return mapAttrs;
	}
	
	/**
	 * Map of Session stored name:entity property name.
	 * 
	 * @return
	 */
	protected Map<String, String> getSessionQueries() {
		HashMap<String, String> queries = new HashMap<String, String>();
		queries.put(QryKeys.DEPT_PA_DEPARTMENT, "department");
		return queries;
	}	
	
	public ActionForward listChildren(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ActionForward relogin=checkLogin(mapping,request);
		if(relogin!=null)return relogin;
		
		DepartmentForm deptForm = (DepartmentForm)form;
		Department parentDept = deptForm.toEntity();

		DepartmentDao deptDao = new DepartmentDao();
		List<Department> children = deptDao.loadChildren(parentDept);
		
		request.setAttribute("departments", children);
		return mapping.findForward("listEntities");
	}

	@Override
	protected AbstractEntityDao<Department> getEntityDao() {
		// TODO Auto-generated method stub
		return new DepartmentDao();
	}	

}
